/* Author: David McCoy dave.mccoy@cospandesign.com
 *
 *     This file is part of DLCM\SubServ.
 *
 *  DLCM\SubServ is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  DLCM\SubServ is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with DLCM\SubServ.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*
 * LcmGen.java
 *
 * Parse LCM files to generate lcm structures
 *
 * Created on Mar 27, 2010, 12:23:36 AM
 */

package com.cospandesign.gui.lcmgen;

import dlcm.StructureManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author cospan
 */
public class LcmGen extends javax.swing.JFrame {

    StructureManager mStructureManager;
    StructureManager TempStructureManager;
    boolean parseSuccessful;

    /** Creates new form LcmGen */
    public LcmGen() {
        initComponents();
        LCMCodeTextArea.setTabSize(1);
        TempStructureManager = new StructureManager();
        ParseOutputTextArea.setText("Tip: drop an LCM file onto the edit box to auto load it\n\n");
    }
    public LcmGen(StructureManager structureManager){
        this();
        mStructureManager = structureManager;
    }

    private void ParseFail(){
        parseSuccessful = false;
        GenerateCButton.setEnabled(false);
        GenerateJavaButton.setEnabled(false);
        GeneratePython.setEnabled(false);
        AddAllStructuresButton.setEnabled(false);
        AddEntity.setEnabled(false);
        RemoveEntity.setEnabled(false);
    }

    private void ParseSuccess(){
        parseSuccessful = true;
        //GenerateCButton.setEnabled(true);
        //GenerateJavaButton.setEnabled(true);
        //generatePython.setEnabled(true);

        
        if (AutoAddCheckBox.isSelected()){
            for (String name : TempStructureManager.StructureMap.keySet()){
                mStructureManager.addStructure(TempStructureManager.StructureMap.get(name));
            }
            TempStructureManager.resetStructures();
        }
        else {
            AddAllStructuresButton.setEnabled(true);
            AddEntity.setEnabled(true);
            RemoveEntity.setEnabled(true);
        }

        UpdateStructureList();
    }

    public void UpdateStructureList(){
        //Update the Dynamic List

        //First with the new stuff
        ArrayList <String> structureNameArray = new ArrayList<String>();

        if (this.TempStructureManager.StructureMap.size() > 0){
            for (String name : TempStructureManager.StructureMap.keySet()){
                structureNameArray.add(name);
            }
        }
        //I don't know how to differentiate Temp, from permanant
/*
        //Then the stuff we have
        if (this.mStructureManager.StructureMap.size() > 0){
            for (String name : mStructureManager.StructureMap.keySet()){
                structureNameArray.add(name);
            }
        }
 */
        DynamicStructureList.removeAll();
        Object [] nameList = new String[structureNameArray.size()];
        nameList = structureNameArray.toArray();
        DynamicStructureList.setListData(nameList);
        for (int i = 0; i < TempStructureManager.StructureMap.size(); i ++){
            DynamicStructureList.setSelectedIndex(i);
        }
    }

    public void SetStructureManager(StructureManager structureManager){
        mStructureManager = structureManager;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        LCMCodeTextArea = new javax.swing.JTextArea();
        ParseButton = new javax.swing.JButton();
        GeneratePython = new javax.swing.JButton();
        GenerateJavaButton = new javax.swing.JButton();
        GenerateCButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        ParseOutputTextArea = new javax.swing.JTextArea();
        AddAllStructuresButton = new javax.swing.JButton();
        OutputDirectoryLocation = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        SetOutputLocationButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        DynamicStructureList = new javax.swing.JList();
        AddEntity = new javax.swing.JButton();
        RemoveEntity = new javax.swing.JButton();
        AutoAddCheckBox = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();
        ExampleStructuresButton = new javax.swing.JButton();

        setTitle("LCM Editor/Parser");
        setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/cospandesign/resources/cospandesign.png")));
        setResizable(false);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        LCMCodeTextArea.setColumns(20);
        LCMCodeTextArea.setRows(5);
        LCMCodeTextArea.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        LCMCodeTextArea.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        LCMCodeTextArea.setDropMode(javax.swing.DropMode.INSERT);
        LCMCodeTextArea.setName("LCMCodeTextArea"); // NOI18N
        jScrollPane1.setViewportView(LCMCodeTextArea);

        ParseButton.setText("Parse");
        ParseButton.setToolTipText("Accellerator: CTRL + Enter");
        ParseButton.setName("ParseButton"); // NOI18N
        ParseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ParseButtonActionPerformed(evt);
            }
        });

        GeneratePython.setText("Generate Python");
        GeneratePython.setEnabled(false);
        GeneratePython.setName("GeneratePython"); // NOI18N
        GeneratePython.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GeneratePythonActionPerformed(evt);
            }
        });

        GenerateJavaButton.setText("Generate Java");
        GenerateJavaButton.setEnabled(false);
        GenerateJavaButton.setName("GenerateJavaButton"); // NOI18N
        GenerateJavaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GenerateJavaButtonActionPerformed(evt);
            }
        });

        GenerateCButton.setText("Generate C");
        GenerateCButton.setEnabled(false);
        GenerateCButton.setName("GenerateCButton"); // NOI18N
        GenerateCButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GenerateCButtonActionPerformed(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        ParseOutputTextArea.setColumns(20);
        ParseOutputTextArea.setRows(5);
        ParseOutputTextArea.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        ParseOutputTextArea.setName("ParseOutputTextArea"); // NOI18N
        jScrollPane2.setViewportView(ParseOutputTextArea);

        AddAllStructuresButton.setText("Add All");
        AddAllStructuresButton.setEnabled(false);
        AddAllStructuresButton.setName("AddAllStructuresButton"); // NOI18N
        AddAllStructuresButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddAllStructuresButtonActionPerformed(evt);
            }
        });

        OutputDirectoryLocation.setName("OutputDirectoryLocation"); // NOI18N

        jLabel1.setText("Output Location");
        jLabel1.setName("jLabel1"); // NOI18N

        SetOutputLocationButton.setText("Set");
        SetOutputLocationButton.setName("SetOutputLocationButton"); // NOI18N

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        DynamicStructureList.setToolTipText("Red entries Have not been saved");
        DynamicStructureList.setName("DynamicStructureList"); // NOI18N
        jScrollPane4.setViewportView(DynamicStructureList);

        AddEntity.setText("Add");
        AddEntity.setEnabled(false);
        AddEntity.setName("AddEntity"); // NOI18N
        AddEntity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddEntityActionPerformed(evt);
            }
        });

        RemoveEntity.setText("Remove");
        RemoveEntity.setEnabled(false);
        RemoveEntity.setName("RemoveEntity"); // NOI18N
        RemoveEntity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveEntityActionPerformed(evt);
            }
        });

        AutoAddCheckBox.setSelected(true);
        AutoAddCheckBox.setText("Auto Add");
        AutoAddCheckBox.setToolTipText("When lcm file is parsed, structures are automatically added to main Structure Manager");
        AutoAddCheckBox.setName("AutoAddCheckBox"); // NOI18N

        jLabel2.setText("Temporary Structures");
        jLabel2.setName("jLabel2"); // NOI18N

        ExampleStructuresButton.setText("Example Structures");
        ExampleStructuresButton.setName("ExampleStructuresButton"); // NOI18N
        ExampleStructuresButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExampleStructuresButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 625, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 625, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ExampleStructuresButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(GeneratePython, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(GenerateCButton, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(GenerateJavaButton, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(SetOutputLocationButton, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(OutputDirectoryLocation, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(ParseButton, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(AddEntity, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(AutoAddCheckBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                        .addComponent(RemoveEntity, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(AddAllStructuresButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(jLabel2))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(GenerateCButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GenerateJavaButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GeneratePython)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(SetOutputLocationButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(OutputDirectoryLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(AddAllStructuresButton)
                    .addComponent(ExampleStructuresButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(AddEntity)
                            .addComponent(RemoveEntity))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AutoAddCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ParseButton))
                    .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ParseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ParseButtonActionPerformed
        try {
            TempStructureManager.parseString(this.LCMCodeTextArea.getText());
        } catch (Exception ex) {
            this.ParseOutputTextArea.append(ex.getMessage() + "\n");
            ParseFail();
            return;
        }
        ParseOutputTextArea.append("Successfully Parsed\n");
        ParseSuccess();
    }//GEN-LAST:event_ParseButtonActionPerformed

    private void GeneratePythonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GeneratePythonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_GeneratePythonActionPerformed

    private void GenerateJavaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GenerateJavaButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_GenerateJavaButtonActionPerformed

    private void GenerateCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GenerateCButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_GenerateCButtonActionPerformed

    private void AddEntityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddEntityActionPerformed
        if (this.DynamicStructureList.getSelectedIndices().length == 0){
            return;
        }
        for (int index : DynamicStructureList.getSelectedIndices()){
            DynamicStructureList.setSelectedIndex(index);
            //Check to see if the selection is in the temp structure
            if (TempStructureManager.StructureMap.containsKey((String)DynamicStructureList.getSelectedValue())){
                //move from tempStructureManager to mStructureManager
                mStructureManager.addStructure(TempStructureManager.getStructure((String)DynamicStructureList.getSelectedValue()));
                TempStructureManager.removeStructure((String)DynamicStructureList.getSelectedValue());
            }
        }
        UpdateStructureList();
    }//GEN-LAST:event_AddEntityActionPerformed

    private void RemoveEntityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveEntityActionPerformed
        if (this.DynamicStructureList.getSelectedIndices().length == 0){
            return;
        }
        for (int index : DynamicStructureList.getSelectedIndices()){
            DynamicStructureList.setSelectedIndex(index);
            TempStructureManager.removeStructure((String)DynamicStructureList.getSelectedValue());

        }
        UpdateStructureList();
    }//GEN-LAST:event_RemoveEntityActionPerformed

    private void AddAllStructuresButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddAllStructuresButtonActionPerformed
        for (String name : TempStructureManager.StructureMap.keySet()){
            mStructureManager.addStructure(TempStructureManager.StructureMap.get(name));
        }
        TempStructureManager.resetStructures();
        UpdateStructureList();
    }//GEN-LAST:event_AddAllStructuresButtonActionPerformed

    private void ExampleStructuresButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExampleStructuresButtonActionPerformed
       // java.awt.Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/cospandesign/resources/cospandesign.png"));

        
        
        InputStream isr = getClass().getResourceAsStream("ExampleStructures.lcm");
        InputStreamReader sr = new InputStreamReader(isr);
        BufferedReader br = new BufferedReader(sr);

        String text = null;

        this.LCMCodeTextArea.setText("");
        try {
            while ((text = br.readLine()) != null) {
                LCMCodeTextArea.append(text + "\n");
            }
        } catch (IOException ex) {
            Logger.getLogger(LcmGen.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            br.close();
        } catch (IOException ex) {
            Logger.getLogger(LcmGen.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_ExampleStructuresButtonActionPerformed



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddAllStructuresButton;
    private javax.swing.JButton AddEntity;
    private javax.swing.JCheckBox AutoAddCheckBox;
    private javax.swing.JList DynamicStructureList;
    private javax.swing.JButton ExampleStructuresButton;
    private javax.swing.JButton GenerateCButton;
    private javax.swing.JButton GenerateJavaButton;
    private javax.swing.JButton GeneratePython;
    private javax.swing.JTextArea LCMCodeTextArea;
    private javax.swing.JTextField OutputDirectoryLocation;
    private javax.swing.JButton ParseButton;
    private javax.swing.JTextArea ParseOutputTextArea;
    private javax.swing.JButton RemoveEntity;
    private javax.swing.JButton SetOutputLocationButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    // End of variables declaration//GEN-END:variables

}
